package net.lulihu.common_util.spring;

import lombok.extern.slf4j.Slf4j;
import net.lulihu.ObjectKit.HttpKit;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;

/**
 * 基于spring封装的常用http工具
 */
@Slf4j
public class SpringHttpKit {

    /**
     * 获取 springMvc 当前的 HttpServletRequest 对象
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null == servletRequestAttributes) return null;
        return servletRequestAttributes.getResponse();
    }

    /**
     * 获取springMvc 当前的 HttpServletRequest 对象
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null == servletRequestAttributes) return null;
        return HttpKit.getRequest(servletRequestAttributes.getRequest());
    }


    /**
     * 获取指定请求头
     *
     * @param key 键
     * @return 根据键获取对应的值
     */
    public static String getHeader(String key) {
        return Objects.requireNonNull(getRequest()).getHeader(key);
    }


    /**
     * 获取所有 头部参数
     */
    public static Map<String, Object> getHeaderParam() {
        return HttpKit.getHeaderParam(getRequest());
    }


    /**
     * 获取客户端真实ip
     */
    public static String getClientIP() {
        return HttpKit.getClientIP(getRequest());
    }

}
